package top.honlnk.common.exception.handler;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import top.honlnk.common.exception.CustomException;
import top.honlnk.common.exception.OCRPartialWarnException;
import top.honlnk.common.result.Result;
import top.honlnk.common.result.WarnResult;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressWarnings("All")
@Slf4j
@ControllerAdvice(basePackages = "top.honlnk.controller")
public class GlobalExceptionHandler {

    @ExceptionHandler(DuplicateKeyException.class)
    @ResponseBody
    public Result<String> duplicateExceptionHandler(@NotNull DuplicateKeyException e) {
        String message = e.getMessage();
        log.error("数据库异常: {}", message);

        if (message.contains("Duplicate entry")) {
            // 存储字段名
            StringBuilder fieldNameBuilder = new StringBuilder();

            // 正则表达式模式
            // 匹配形如 "Duplicate entry 'value' for key 'table.column'" 的字符串
            String pattern = "Duplicate entry '(.*?)' for key '(.*?)'";
            Pattern r = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
            Matcher m = r.matcher(message);

            if (m.find()) {
                String fieldName = m.group(1);
                // 拼接字段名，中间用“、”隔开
                fieldNameBuilder.append(fieldName);
            }

            // 最终的字段名字符串
            String fieldNames = fieldNameBuilder.toString();

            // 构造返回结果
            return Result.error( fieldNames + "已存在，请勿重复添加");
        } else {
            return Result.error("数据库异常" + e);
        }
    }
    /**
     * 参数校验失败
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result<String> methodExceptionHandler(@NotNull MethodArgumentNotValidException e) {
        String message = e.getMessage();


        if (message.contains("Failed to convert property value")) {
            // 存储字段名
            StringBuilder fieldNameBuilder = new StringBuilder();

            // 正则表达式模式
            String pattern = "Failed to convert property value of type.*?for property '(.*?)'; For input string: \"(.*?)\"";
            Pattern r = Pattern.compile(pattern, Pattern.DOTALL);
            Matcher m = r.matcher(message);

            while (m.find()) {
                String fieldName = m.group(1);
                // 拼接字段名，中间用“、”隔开
                if (!fieldNameBuilder.isEmpty()) {
                    fieldNameBuilder.append("、");
                }
                fieldNameBuilder.append(fieldName);
            }
            // 最终的字段名字符串
            String fieldNames = fieldNameBuilder.toString();

            // 构造返回结果
            log.error("参数校验失败: {}", fieldNames + "参数类型格式不符合要求");
            return Result.error(fieldNames + "参数类型格式不符合要求");
        } else {
            return Result.error("参数校验失败" + e);
        }
    }

    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public Result<String> CustomException(HttpServletRequest request, CustomException e) {
        log.error("自定义异常: {}", e.getMsg());
        return Result.error(e.getMsg());
    }

    @ExceptionHandler(OCRPartialWarnException.class)
    @ResponseBody
    public Result<WarnResult> OCRPartialWarnException(HttpServletRequest request, OCRPartialWarnException e) {
        log.warn("自定警告义异常: {}", e.getWarn());
        log.warn("自定警告义异常: {}", e.getDataVO());

        return Result.warn(WarnResult.builder()
                        .warn(e.getWarn())
                        .dataVO(e.getDataVO())
                .build());
    }

    // 统一异常处理@ExceptionHandler,主要用于Exception
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result<String> Exception(HttpServletRequest request, Exception e) {
        log.error("全局异常捕获: ", e);
        return Result.error("系统异常");
    }
}